<?php
class Api
{
	private $module;
	private $action;
	
	private $reqUrl;
	private $appKey;
	private $secret;
	
	public function __construct($module,$action='index')
	{
		$this->module = $module;
		$this->action = $action;
		
		$config = C('LtConfig')->get('api');
		$this->reqUrl = $config['url'];
		$this->appKey = $config['key'];
		$this->secret = $config['secret'];
	}
	
	public function fetch($fields='',$where='',$join='',$orderby='')
	{
		$params['op'] = 'fetch';
		$params['fields'] = $fields;
		$params['where'] = $where;
		$params['join'] = $join;
		$params['orderby'] = $orderby;
		
		return $this->get($params);
	}
	
	public function fetchRows($fields='',$where='',$join='',$orderby='',$limit='',$start=0)
	{
		$params['op'] = 'fetchrows';
		$params['fields'] = $fields;
		$params['where'] = $where;
		$params['join'] = $join;
		$params['orderby'] = $orderby;
		$params['limit'] = $limit;
		$params['start'] = $start;
		
		return $this->get($params);
	}
	
	public function insert($args = null)
	{
		$params['op'] = 'insert';
		$params['data'] = $args;
		
		return $this->get($params);
	}
	
	public function updateRows($where, $args)
	{
		$params['op'] = 'updaterows';
		$params['where'] = $where;
		$params['data'] = $args;
		
		return $this->get($params);
	}
	
	public function deleteRows($args = null)
	{
		$params['op'] = 'deleterows';
		$params['where'] = $args;
		
		return $this->get($params);
	}
	
	private function get($params)
	{
		$ret = $this->req($params);
		if(empty($ret))
		{
			return false;
		}
		
		$ret = json_decode($ret, true);
		if($ret['code']!=200)
		{
			return false;
		}
		
		return $ret['data']['result'];
	}
	
	private function req($params)
	{
		$reqUrl = $this->reqUrl.'module='.$this->module.'&action='.$this->action;
		$tmp = array('key'=>$this->appKey,'secret'=>$this->secret,'v' => '1.0');
		$params = array_merge($tmp, $params);
		foreach($params as $k=>$v)
		{
			if(is_array($v))
			{
				$params[$k] = json_encode($v);
			}
		}
		$data = http_build_query($params);
		
		$timeout = 3;

		$allUrlOpen = ini_get('all_url_fopen');
		if(function_exists('file_get_contents') && (empty($allUrlOpen) || strtolower($allUrlOpen)=='on'))
		{
			//用file_get_contents抓取
			$opts = array(
					    'http'=>array(
					    'method'=>"POST",  
					    'header'=>"Content-type: application/x-www-form-urlencoded\r\n".  
					               "Content-length:".strlen($data)."\r\n" .   
					               "\r\n",  
					    'content' => $data,  
					    'timeout'=>$timeout,
			)
			);
			$context = stream_context_create($opts);
			return @file_get_contents($reqUrl, false, $context);
		}

		if(function_exists('fsockopen'))
		{
			$urlInfo = parse_url($reqUrl);
			$host = $urlInfo['host'];
			$sock = fsockopen($host, 80, $errno, $errstr, $timeout);
			;
			if (!$sock)
			{
				return false;
			}
			
			socket_set_timeout($sock, $timeout);
				
			$out = "POST ".$reqUrl." HTTP/1.1\r\n";
			$out .= "Host: " . $host . "\r\n";
			$out .= "Content-type: application/x-www-form-urlencoded\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Content-length:".strlen($data)."\r\n\r\n";
			$out .= $data."\r\n";
			
			$info = '';
			fwrite($sock, $out);
			while (!feof($sock))
			{
				$info = $info . fgets($sock, 4096);
			}
			fclose($sock);
			
			if(empty($info))
			{
				return false;
			}
			
			$tmp = explode("\r\n\r\n", $info, 2);
			if(!eregi("^HTTP/1.. 200", $tmp[0]))
			{
				return false;
			}
			
			return $tmp[1];
		}

		if(function_exists('curl_init'))
		{
			$ch = curl_init($reqUrl);
			curl_setopt($ch, CURLOPT_POST, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: */*', 'Content-Type: application/x-www-form-urlencoded'));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			$info = curl_exec($ch);
			curl_close($ch);
			
			return $info;
		}

		return false;
	}

	private function getArrayData($data,$format)
	{
		$ret = json_decode($data,true);
		
		return $ret;
	}

	private function checkFields($allow,$fields)
	{
		if(!is_array($fields))
		{
			$fields = explode(',', $fields);
		}
		
		if(!empty($fields))
		{
			$tmp	= array();
			foreach($fields as $f)
			{
				if(in_array($f, $allow))
				{
					$tmp[]	= $f;
				}
			}
			$fields	= $tmp;
		}
		
		if(empty($fields))
		{
			$fields		= $allow;
		}
		
		$fields = implode(',', $fields);
		
		return $fields;
	}
}
?>